import nodePath from "path";
import nodeUrl from "url";
import nodeFileSystem from "fs";

export const PROJECT_ROOT = nodePath.join(__dirname, "../..");

export const PROJECT_STATIC = nodePath.join(PROJECT_ROOT, "static");

export const PROJECT_CACHE = nodePath.join(PROJECT_ROOT, "cache");


export function pathToUrl(path: string): URL {
  return nodeUrl.pathToFileURL(path);
}

export async function readJson<T>(jsonPath: string): Promise<T> {
  const jsonContent = await nodeFileSystem.promises.readFile(jsonPath, "utf8");
  return JSON.parse(jsonContent);
}

export async function writeJson(jsonPath: string, jsonInfo: any) {
  return nodeFileSystem.promises.writeFile(jsonPath, JSON.stringify(jsonInfo));
}

export function isStartWithWebProtocol(pathStr: string) {
  return pathStr.startsWith("https://") || pathStr.startsWith("http://");
}

export function isStartWithProtocol(pathStr: string) {
  return pathStr.startsWith("file://") || isStartWithWebProtocol(pathStr);
}

export function posixJoinPath(...pathParts: string[]) {
  return toPosixPath(nodePath.join(...pathParts));
}

export function toPosixPath(pathStr: string): string {
  return pathStr.replace(/\\{1,2}/g, "/");
}

export {
  nodePath,
  nodeFileSystem
};
